import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import { loginApi, logoutApi } from "@/api/acl/login";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [], //菜单权限列表
  }),

  actions: {
    // 登陆
    async login(username: string, password: string) {
      // 发送请求登陆
      const { token } = await loginApi(username, password);
      // 登录成功将token存储起来
      // token将来就会在请求拦截器使用
      this.token = token; // 存在pinia中（方便各个地方都可以使用）
      setToken(token); // 存在localStorage中（持久化存储，下次刷新数据还在）
    },

    getInfo() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.name = "admin";
          this.avatar =
            "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
          this.menuRoutes = staticRoutes;
          resolve({ name: this.name, avatar: this.avatar, token: this.token });
        }, 1000);
      });
    },

    // 登出
    async reset() {
      // 删除服务器的token
      await logoutApi();
      // 删除local中保存的token
      removeToken();
      // 删除pinia中的数据
      this.token = "";
      this.name = "";
      this.avatar = "";
    },
  },
});
